<!DOCTYPE html>
<html>
<head>
    <title>定时任务</title>
    <style>
        .schedule-form {
            max-width: 600px;
            margin: 20px auto;
        }
        .time-picker {
            margin: 10px 0;
        }
    </style>
</head>
<body>
    <div class="schedule-form">
        <h2>定时任务管理</h2>
        <select id="scheduleDevice">
            <option value="device1">设备1</option>
            <option value="device2">设备2</option>
        </select>
        <input type="time" id="scheduleTime" class="time-picker">
        <select id="scheduleCommand">
            <option value="water_on">开启洒水</option>
            <option value="water_off">关闭洒水</option>
        </select>
        <button onclick="addSchedule()">添加任务</button>

        <div id="taskList"></div>
    </div>

    <script>
        async function loadSchedules() {
            const res = await fetch('/api/schedules')
            const tasks = await res.json()
            document.getElementById('taskList').innerHTML = tasks
                .map(task => `
                    <div class="task-item">
                        ${task.device} 每天 ${task.time} 执行 ${task.command}
                        <button onclick="deleteTask('${task.id}')">删除</button>
                    </div>
                `).join('')
        }

        async function addSchedule() {
            const task = {
                device: document.getElementById('scheduleDevice').value,
                command: document.getElementById('scheduleCommand').value,
                schedule: {
                    hour: document.getElementById('scheduleTime').value.split(':')[0],
                    minute: document.getElementById('scheduleTime').value.split(':')[1]
                }
            }

            await fetch('/api/schedules', {
                method: 'POST',
                headers: {'Content-Type': 'application/json'},
                body: JSON.stringify(task)
            })
            loadSchedules()
        }

        async function deleteTask(id) {
            await fetch(`/api/schedules?id=${id}`, {method: 'DELETE'})
            loadSchedules()
        }

        // 初始化加载
        loadSchedules()
    </script>
</body>
</html>